/**
 * 网络请求工具
 * 封装微信小程序的wx.request
 */

// API基础URL - 根据实际情况修改
const BASE_URL = 'http://127.0.0.1:8000'

// 请求响应接口定义
interface ApiResponse<T = any> {
  success: boolean
  message: string
  data: T
}

// 请求配置接口
interface RequestConfig {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  data?: any
  header?: any
  showLoading?: boolean
  loadingText?: string
}

/**
 * 统一请求方法
 */
export function request<T = any>(config: RequestConfig): Promise<ApiResponse<T>> {
  const {
    url,
    method = 'GET',
    data = {},
    header = {},
    showLoading = true,
    loadingText = '加载中...'
  } = config

  // 显示加载提示
  if (showLoading) {
    wx.showLoading({
      title: loadingText,
      mask: true
    })
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + url,
      method: method,
      data: data,
      header: {
        'Content-Type': 'application/json',
        ...header
      },
      success: (res) => {
        if (showLoading) {
          wx.hideLoading()
        }

        const response = res.data as ApiResponse<T>
        
        if (response.success) {
          resolve(response)
        } else {
          // 业务错误
          wx.showToast({
            title: response.message || '请求失败',
            icon: 'none',
            duration: 2000
          })
          reject(response)
        }
      },
      fail: (err) => {
        if (showLoading) {
          wx.hideLoading()
        }
        
        wx.showToast({
          title: '网络请求失败',
          icon: 'none',
          duration: 2000
        })
        reject(err)
      }
    })
  })
}

/**
 * GET请求
 */
export function get<T = any>(url: string, data?: any, showLoading = true): Promise<ApiResponse<T>> {
  return request<T>({
    url,
    method: 'GET',
    data,
    showLoading
  })
}

/**
 * POST请求
 */
export function post<T = any>(url: string, data?: any, showLoading = true): Promise<ApiResponse<T>> {
  return request<T>({
    url,
    method: 'POST',
    data,
    showLoading
  })
}

/**
 * PUT请求
 */
export function put<T = any>(url: string, data?: any, showLoading = true): Promise<ApiResponse<T>> {
  return request<T>({
    url,
    method: 'PUT',
    data,
    showLoading
  })
}

/**
 * DELETE请求
 */
export function del<T = any>(url: string, data?: any, showLoading = true): Promise<ApiResponse<T>> {
  return request<T>({
    url,
    method: 'DELETE',
    data,
    showLoading
  })
}